/**
 iTextUploader
 (C) 2008 MyselftDev (myselftdev@gmail.com)
 
 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.
 
 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

/* Revision: $Id: HomeView.m 65 2009-02-15 14:42:06Z myselftdev $ */

#import "HomeView.h"

/*// Dummy interface to avoid a warning.
@interface NSURLRequest (iTextUploader)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString*)host;
+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString*)host;
@end*/

@implementation HomeView

@synthesize homeWebView;

-(id)init
{
	if ((self = [super init]))
	{
		isWorking = NO;
		alertDisplayed = NO;
	}
	return self;
}

-(void)setMainView: (MainView*)view preferencesData:(PreferencesData*)data
{
	mainView = [view retain];
	preferencesData = [data retain];
	
	CGRect contentRect = CGRectMake(0.0, 0.0, 320.0, (460.0 - 93.0));
	homeWebView = [ [UIWebView alloc] initWithFrame:contentRect];
	homeWebView.delegate = self;
	[mainView.contentView addSubview:homeWebView];
	
	loadingView = [ [AlertBox alloc] initAlertBox];
	loadingView.hidden = YES;
	
	[self loadHome];
}

-(void)isGoingToVisible
{
	UIBarButtonItem *refreshButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(loadHome)];
	[refreshButton autorelease];
	[mainView.navItem setRightBarButtonItem:refreshButton animated:NO];
}

-(void)isGoingToHidden
{
	[mainView.navItem setRightBarButtonItem:nil animated:NO];
}

-(void) loadHome
{
	if(!isWorking)
	{
		//NSLog(@"Requesting home");
		isWorking = YES;
		loadingView.hidden = NO;
		
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
		
		NSString *URLString = [NSString stringWithFormat:@"%@%@", @BASEURL, [@"remoteclient.php?appversion=" stringByAppendingString:@APPVERSION]];
		NSURL *theURL = [NSURL URLWithString:URLString];
		
		NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
		[theRequest setHTTPMethod: @"POST"];
		
		NSString *requestString = [NSString stringWithFormat:@"username=%@&password=%@", 
			encodeURL((CFStringRef) [preferencesData getData:@"username"]),
			encodeURL((CFStringRef) [preferencesData getData:@"password"])];
		
		[theRequest setHTTPBody:[requestString dataUsingEncoding:NSASCIIStringEncoding]];
		
		//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[theURL host]];
		
		[homeWebView loadRequest:theRequest];
	}
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
	loadingView.hidden = YES;
	
	// If isWorking = NO, this function has been called when loading fallback page
	if(isWorking)
	{
		NSString *fatalError = [homeWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('fatal_error').innerHTML"];
		if([fatalError isEqualToString:@"0"] || [fatalError isEqualToString:@""])
		{
			NSInteger loggedIn = [[homeWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('logged_in').innerHTML"] intValue];
			
			if(loggedIn == 0)
			{
				NSString *loginErrorMessage = [homeWebView stringByEvaluatingJavaScriptFromString:@"document.getElementById('login_error').innerHTML"];
				
				if(![loginErrorMessage isEqualToString:@""])
				{
					UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:@"Login error" message:loginErrorMessage delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
					[alertMessage show];
					[alertMessage autorelease];
				}
			}
			
			mainView.internetConnectionAvailable = (loggedIn == 0) ? NO : YES;
		}
		else
		{
			[homeWebView loadHTMLString:[@"<h1>Error</h1>" stringByAppendingString:fatalError] baseURL:nil];
			mainView.internetConnectionAvailable = NO;
		}
		isWorking = NO;
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	}
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
	isWorking = NO;
	mainView.internetConnectionAvailable = NO;
	
	NSURL *errorURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"ConnectionError" ofType:@"html"]];
	NSURLRequest *aRequest=[NSURLRequest requestWithURL:errorURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
	[homeWebView loadRequest:aRequest];
	
	if(!alertDisplayed)
	{
		UIAlertView *alertMessage = [ [UIAlertView alloc] initWithTitle:@"Connection error"	message:@"You must be connected to the Internet to use this application." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
		[alertMessage show];
		[alertMessage autorelease];
		[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
		
		alertDisplayed = YES;
	}
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
	NSURL *theURL = [request URL];
	NSURL *ourURL = [NSURL URLWithString:@BASEURL];
	
	if([@"file" isEqualToString:[theURL scheme]] || [@"about" isEqualToString:[theURL scheme]] ||
	   [[ourURL host] isEqualToString:[theURL host]])
	{
		return YES;
	}
	
	[[UIApplication sharedApplication] openURL:theURL];
	return NO;
}


-(void)dealloc
{
	[homeWebView release];
	[mainView release];
	[preferencesData release];
	[loadingView release];
	
	[super dealloc];
}
@end
